package org.stuty.jettyserver;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 * Created by dws on 2018/4/2.
 */
public class AppLancher {

    private static final int DEFAULT_PORT = 8082;
    private static Server server;

    public static void main(String[] args) throws Exception {
        AppLancher.startJetty(getPortFromArgs(args));
    }

    private static int getPortFromArgs(String[] args) {
        if (args.length > 0) {
            try {
                return Integer.valueOf(args[0]);
            } catch (NumberFormatException ignore) {
                System.out.println(ignore);
            }
        }
        return DEFAULT_PORT;
    }

    private static void startJetty(int port) throws Exception {
        server = new Server(port);
        server.setHandler(getWebAppContext());
        server.start();
        server.join();
    }

    public static void stopJetty() throws Exception {
        server.stop();
    }

    private static WebAppContext getWebAppContext() {
        WebAppContext context = new WebAppContext("webapp","/");
        context.setDescriptor("webapp/WEB-INF/web.xml");
        context.setResourceBase("src/main/webapp");
        context.setParentLoaderPriority(true);
        context.setClassLoader(Thread.currentThread().getContextClassLoader());
        context.setConfigurationDiscovered(true);
        context.setParentLoaderPriority(true);
        return context;
    }


}
